import gradio as gr
from step1 import Step1
from step2 import Step2
from step3 import Step3
from database import *

def save_database(AccessKey: str, SecretKey: str):
    user_id = get_user_count() + 1
    access_key = AccessKey
    secret_key = SecretKey
    store_user_keys(user_id, access_key, secret_key)

def init_database():
    count = get_user_count()
    print("user count: ",count)
    if count <= 0:
        gr.Warning("请移至[设置]创建至少一个用户以存储密钥",visible=True,duration=5)


def create_key_input_module():
    """创建密钥输入模块"""
    with gr.Blocks() as key_input_module:
        gr.Markdown("## 输入您的 AccessKey 和 SecretKey")
        access_key_input = gr.Textbox(label="AccessKey", placeholder="请输入您的 AccessKey")
        secret_key_input = gr.Textbox(label="SecretKey", placeholder="请输入您的 SecretKey", type="password")
        submit_button = gr.Button("提交")
        output_message = gr.Textbox(label="状态", interactive=False)
        # drop box for selecting user_id
        user_id_dropdown = gr.Dropdown(label="选择用户", choices=[i for i in range(1, get_user_count() + 1)],interactive=True)
        def on_user_id_change(x):
            USER_NOW["value"] = x
            print("当前用户ID已更改为:", USER_NOW["value"])
        user_id_dropdown.change(on_user_id_change, inputs=user_id_dropdown)

        def submit_keys(access_key, secret_key):
            save_database(access_key, secret_key)
            return gr.Dropdown(label="选择用户", choices=[i for i in range(1, get_user_count() + 1)],interactive=True), "密钥已保存！"

        submit_button.click(submit_keys, inputs=[access_key_input, secret_key_input], outputs=[user_id_dropdown, output_message])

    return key_input_module

def create_main_app():
    """创建主应用"""
    with gr.Blocks(title="模块化Gradio应用") as main_app:
        gr.Markdown("# 我的主应用")
        gr.Markdown("这个应用由多个独立模块组成")
        
        # 嵌套第一个模块
        with gr.Tab("姿势生成人物"):
            step1 = Step1()
            module1 = step1.create_step()
        
        # 嵌套第二个模块
        with gr.Tab("更换背景图像"):
            step2 = Step2()
            module2 = step2.create_step()
        
        #3
        with gr.Tab("更换风格"):
            step3 = Step3()
            module3 = step3.create_step()

        # 可以添加更多模块...
        with gr.Tab("设置"):
            module4 = create_key_input_module()
    
    return main_app

if __name__ == "__main__":
    app = create_main_app()
    app.queue().launch()